import { getBookingScheduleRule, findScheduleList } from '../../../api';
import { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Pagination,
  Divider,
  Card,
  Space,
  Button,
  Spin,
  Empty,
} from 'antd';
import {
  getScheduleListDataInfo,
  toggleShowLoginModal,
} from '../../../redux/actions';
import { useParams } from 'react-router-dom';
import { connect } from 'react-redux';
import './index.css';
import { useNavigate } from 'react-router-dom';
import moment from 'moment';
import Countdown from 'react-countdown';

const Schedule = (props) => {
  const {
    list,
    total,
    baseMap,
    listLoading,
    getScheduleListDataInfo,
    toggleShowLoginModal,
    token,
  } = props;
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(6);
  const { hoscode, depcode } = useParams();
  const [activeWorkDate, setActiveWorkDate] = useState('');
  const [scheduleList, setScheduleList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [canAppointment, setCanAppointment] = useState(false);
  const [countDown, setCountDown] = useState(0);
  const navigate = useNavigate();

  useEffect(async () => {
    await getScheduleListDataInfo({
      page,
      limit,
      hoscode,
      depcode,
    });
    if (list.length > 0) {
      const pos =
        list.findIndex((_) => _.status === 0 && _.availableNumber > 0) || 0;
      const initWorkDate = list[pos].workDate;
      setActiveWorkDate(initWorkDate);
    }
  }, [page, token, list.length]);

  useEffect(async () => {
    if (activeWorkDate.length != 0) {
      setLoading(true);
      const scheduleListData = await findScheduleList(
        hoscode,
        depcode,
        activeWorkDate
      );
      if (!scheduleListData) {
        setLoading(false);
        toggleShowLoginModal(true);
        return;
      }
      setLoading(false);
      await setScheduleList(scheduleListData);
    }
  }, [activeWorkDate, token]);

  const onChangePage = (page) => {
    setPage(page);
  };

  const getClass = (_) => {
    let className = 'cardNoNumberBg';
    if (_.status == 0) {
      if (_.availableNumber == -1) {
        // 无号
        className = 'cardNoNumberBg';
      } else if (_.availableNumber == 0) {
        // 约满
        className = 'cardFullNumberBg';
      } else {
        // 有号
        className = 'cardHaveNumberBg';
      }
    } else if (_.status == 1) {
      // 即将放号
      className = 'cardNoNumberBg';
    } else {
      // 停止挂号
      className = 'cardNoNumberBg';
    }
    if (_.workDate == activeWorkDate) {
      className += ' active';
    }

    return className;
  };

  const getCurDate = () => {
    let datetime = new Date();
    let year = datetime.getFullYear();
    let month =
      datetime.getMonth() + 1 < 10
        ? '0' + (datetime.getMonth() + 1)
        : datetime.getMonth() + 1;
    let date =
      datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate();
    return year + '-' + month + '-' + date;
  };

  const onCardClick = (_) => {
    // 即将放号
    if (_.status == 1) {
      const countDownReleaseTime = moment(
        getCurDate() + ' ' + baseMap.releaseTime
      );
      const currentTime = moment();

      const countDownDiffTime = currentTime.diff(countDownReleaseTime);
      setCountDown(countDownDiffTime);
    } else {
      setCountDown(0);
    }
    if (_.status == 0 && _.availableNumber > 0) {
      setCanAppointment(true);
    } else {
      setCanAppointment(false);
    }
    setActiveWorkDate(_.workDate);
  };

  const gotoBookSchedule = (id) => {
    navigate(`/hospital/booking/${id}`);
  };

  if (!token) {
    return (
      <Empty
        image={Empty.PRESENTED_IMAGE_DEFAULT}
        description='预约挂号，请先登陆'
      ></Empty>
    );
  }
  return (
    <div className='m-l-30 m-r-30'>
      <h2 className='m-b-10'>
        {baseMap.hosname} | {baseMap.bigname}
      </h2>
      <div className='m-b-10'>{baseMap.depname}</div>
      <center className='m-b-20'>{baseMap.workDateString}</center>
      <Row gutter={16}>
        {list.map((_) => {
          return (
            <Col key={_.workDate} span={4}>
              <Card
                className={getClass(_)}
                title={
                  <span style={{ fontSize: '12px', color: 'white' }}>
                    {_.workDate}
                  </span>
                }
                extra={
                  <span style={{ fontSize: '12px', color: 'white' }}>
                    {_.dayOfWeek}
                  </span>
                }
                onClick={() => onCardClick(_)}
              >
                <center>
                  {_.status == 0 &&
                    (_.availableNumber == -1 ? (
                      '无号'
                    ) : _.availableNumber == 0 ? (
                      '约满'
                    ) : (
                      <span style={{ color: '#4990f2' }}>有号</span>
                    ))}
                  {_.status == 1 && '即将放号'}
                  {_.status == -1 && '停止挂号'}
                </center>
              </Card>
            </Col>
          );
        })}
      </Row>
      <Pagination
        className='m-t-10 m-b-30'
        current={page}
        total={total}
        onChange={onChangePage}
        pageSize={limit}
      />

      {loading && <Spin></Spin>}

      {countDown > 0 ? (
        <center>
          <span>明天 {baseMap.releaseTime} 点放号</span>
          <br />
          <div style={{ fontSize: '30px' }} className='m-b-30'>
            倒计时：<Countdown date={Date.now() + countDown}></Countdown>
          </div>
        </center>
      ) : (
        scheduleList &&
        scheduleList.length > 0 && (
          <>
            <Divider orientation='left' plain>
              上午号源
            </Divider>

            {scheduleList.map((_) => {
              if (_.workTime == 0) {
                return (
                  <div key={_.id}>
                    <Row>
                      <Col flex='auto'>
                        <div
                          className='m-b-10'
                          style={{ fontWeight: '900', color: 'black' }}
                        >
                          {_.title} {_.docname && <>| {_.docname}</>}
                        </div>
                        <div>{_.skill}</div>
                      </Col>
                      <Col flex='auto'>
                        <Row justify='end'>
                          <Col flex='80px'> ￥{_.amount}元</Col>
                          <Col flex='80px'> 剩余({_.availableNumber})</Col>
                          {canAppointment && (
                            <Col flex='80px'>
                              <Button
                                type='primary'
                                onClick={() => gotoBookSchedule(_.id)}
                              >
                                <span style={{ color: 'white' }}>预约</span>
                              </Button>
                            </Col>
                          )}
                        </Row>
                      </Col>
                    </Row>
                    <div className='m-b-30'></div>
                  </div>
                );
              }
            })}

            <Divider orientation='left' plain>
              下午号源
            </Divider>

            {scheduleList.map((_) => {
              if (_.workTime == 1) {
                return (
                  <div key={_.id}>
                    <Row>
                      <Col flex='auto'>
                        <div
                          className='m-b-10'
                          style={{ fontWeight: '900', color: 'black' }}
                        >
                          {_.title} {_.docname && <>| {_.docname}</>}
                        </div>
                        <div>{_.skill}</div>
                      </Col>
                      <Col flex='auto'>
                        <Row justify='end'>
                          <Col flex='80px'> ￥{_.amount}元</Col>
                          <Col flex='80px'> 剩余({_.availableNumber})</Col>
                          {canAppointment && (
                            <Col flex='80px'>
                              <Button
                                type='primary'
                                onClick={() => gotoBookSchedule(_.id)}
                              >
                                <span style={{ color: 'white' }}>预约</span>
                              </Button>
                            </Col>
                          )}
                        </Row>
                      </Col>
                    </Row>
                    <div className='m-b-30'></div>
                  </div>
                );
              }
            })}
          </>
        )
      )}
    </div>
  );
};

const mapStateToProps = (state) => {
  return {
    list: state.schedule.listData.list,
    total: state.schedule.listData.total,
    baseMap: state.schedule.listData.baseMap,
    listLoading: state.schedule.listLoading,
    token: state.user.token,
  };
};
const mapDispatchToProps = { getScheduleListDataInfo, toggleShowLoginModal };
export default connect(mapStateToProps, mapDispatchToProps)(Schedule);
